package com.javalong.mir.common.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLUtils {
	/**
	 * xml请求转map
	 */
	public static Map<String, String> parseRequestXml(HttpServletRequest request) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		InputStream inputStream = request.getInputStream();
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		Element root = document.getRootElement();
		List<Element> elementList = root.elements();
		for (Element e : elementList)
			map.put(e.getName(), e.getText());
		inputStream.close();
		inputStream = null;
		return map;
	}

	/**
	 * @param map
	 */
	public static String parseMap2Xml(Map<String, String> map) {
		if (map == null) {
			return null;
		}
		Element root = DocumentHelper.createElement("xml");
		Document document = DocumentHelper.createDocument(root);
		for (Entry<String, String> entry : map.entrySet()) {
			String qName = entry.getKey();
			String text = entry.getValue();
			Element element = DocumentHelper.createElement(qName);
			element.setText(text);
			root.add(element);
		}
		System.out.println(document.asXML());
		return document.asXML();
	}

}
